package org.anyin.gitee.cloud.lib.core.web.filter;

import org.anyin.gitee.cloud.lib.core.utils.RequestIdUtil;
import org.anyin.gitee.cloud.lib.core.web.context.WebContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

public class RequestIdFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
            MDC.put("REQUEST_ID", this.getRequestId());
            try {
                filterChain.doFilter(request, response);
            } finally {
                RequestIdUtil.removeRequestId();
                MDC.clear();
            }

        }
    }

    @Override
    public void destroy() {
    }

    private String getRequestId(){
        // 优先从header获取，gateway会设置
        HttpServletRequest request = WebContext.getRequest();
        String requestId = request.getHeader("x-request-id");
        if(StringUtils.isEmpty(requestId)){
            RequestIdUtil.generateRequestId();
            return RequestIdUtil.getRequestId().toString();
        }
        // 设置回RequestIdUtils
        UUID uuid = UUID.fromString(requestId);
        RequestIdUtil.generateRequestId(uuid);
        return requestId;
    }
}
